import React, {useEffect, useState} from 'react';
import {useIsFocused} from '@react-navigation/native';
import {
  View,
  Button,
  Text,
  TextInput,
  StyleSheet,
  Dimensions,
  Image,
  Modal,
} from 'react-native';
import '../utils/myglobal.js';
import mystyles from './mystyles';
import {bcos_rpc} from '../utils/bcosproxy_util';
import {isObject} from '../utils/bcosutils';
import eventBus from '../utils/ContractEventBus';
import {setProxyUrls} from '../utils/myglobal';
let isListener = false;
const BlockInfo = props => {
  const [blocknum, setBlockNum] = useState(0);
  const [counter, setCounter] = useState(0);
  const [failCounter, setFailCounter] = useState(0);
  let tabName = '';
  //console.log('BlockInfo start: ', props);
  if (props.tabname != undefined) {
    tabName = props.tabname;
  }

  function updateBlockNum() {
    //var newnum = blocknum => blocknum + 1;
    bcos_rpc('getBlockNumber', [], tabName).then(res => {
      if (res instanceof Object || res === undefined || res.length == 0) {
        console.error('updateBlockNum error ', res);
        setFailCounter(failCounter => failCounter + 1);
      } else {
        //console.log(`${tabName} ,focus :${isFocused}: updateBlockNum success `, res);
        setBlockNum(res);
        setCounter(counter => counter + 1);
      }
    });
  }
  const eventTag = 'tx';
  function onMyEvent(data) {
    console.log('Event got --> : ', tabName, data);
    if (isFocused) {
      updateBlockNum();
    }
  }

  const isFocused = useIsFocused();

  if (isFocused) {
    //2023.05.25 focus逻辑不可靠，不可见的tab里的组件也是focus，有待调试确认
  } else {
  }

  useEffect(() => {
    const interval = setInterval(() => {
      updateBlockNum();
    }, 5000);
    console.log('BlockInfo Event-->Listen Event tx', onMyEvent);
    //todo:调试如何只监听一次
    eventBus.on(eventTag, onMyEvent);
    return () => {
      clearInterval(interval); // 清除定时器
      console.log('BlockInfo Event-->removeListener tx', onMyEvent);
      eventBus.off(eventTag, onMyEvent);
    };
  }, []);
  return (
    <>
      <View style={{flexDirection: 'row'}}>
        <Text style={[mystyles.SubTitle, {width: 150}]}>区块高度: </Text>
        <Text style={mystyles.text}>{blocknum} </Text>
        <Text style={[mystyles.text, {flex: 1}]}>
          | 计数:{counter}({failCounter})
        </Text>
      </View>
    </>
  );
};

export default BlockInfo;
